package com.pengxh.app.realityshow.netty;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

/**
 * @className: LongConnectService
 * @description: TODO
 * @author: Pengxh
 * @email: 290677893@qq.com
 * @date: 2019/11/15 22:54
 */
public class LongConnectService extends Service implements NettyListener {

    private static final String TAG = "LongConnectService";
    private ConfigBroadcastReceiver configBroadcast = null;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        if (configBroadcast == null) {
            configBroadcast = new ConfigBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("action.getConfig");
            registerReceiver(configBroadcast, intentFilter);
        }
    }

    class ConfigBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && action.equals("action.getConfig")) {
                Log.d(TAG, "onReceive: " + action);
                String ip = intent.getStringExtra("ip");
                int port = Integer.parseInt(intent.getStringExtra("port"));

                BootstrapClient nettyClient = new BootstrapClient(ip, port);
                if (!nettyClient.getConnectStatus()) {
                    nettyClient.setListener(LongConnectService.this);
                    nettyClient.connect();
                } else {
                    nettyClient.disconnect();
                }
            }
        }
    }

    @Override
    public void onMessageResponse(Object msg) {
        Log.d(TAG, "服务器的想消息: " + msg);
        //更新页面
        String serverMsg = msg.toString().trim();
        if (serverMsg.equals("")) {
            Log.e(TAG, "onMessageResponse: ", new Throwable());
        } else {
            Intent intent = new Intent();
            intent.setAction("action.updateView");
            intent.putExtra("serverMsg", serverMsg);
            sendBroadcast(intent);
        }
    }

    @Override
    public void onServiceStatusConnectChanged(int statusCode) {
        Log.d(TAG, "onServiceStatusConnectChanged: " + statusCode);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        if (configBroadcast != null) {
            unregisterReceiver(configBroadcast);
        }
    }
}
